package dy.spec.edu.week15_home01;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;


public class ViewPagerAdapter extends PagerAdapter {

    List<BasePager> pagerList = new ArrayList<>();

    public ViewPagerAdapter(List<BasePager> list) {
        pagerList = list;
    }
    private final List<Fragment> mFragmentList = new ArrayList<>();
    public ViewPagerAdapter(FragmentManager manager) {
        super();
    }
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        BasePager pager = pagerList.get(position);
        View view = pager.rootView;
        if (!pager.isInitData()) {
            pager.initData();
        }
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(pagerList.get(position).rootView);
    }

    @Override
    public int getCount() {
        return pagerList.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    public void addFragment(Fragment fragment) {
        mFragmentList.add(fragment);
    }
}
